package com.hxkj.client.service.taglib.directive;

import com.hxkj.client.service.FriendlyLinkServiceClient;
import com.hxkj.domain.po.FriendlyLink;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import static com.hxkj.client.service.taglib.config.LableConstant.CMS_FRIENDLYLINK;

/**
 * 自定义标签
 * 友情链接
 *
 * @author chenfangzhou 2018/09/14
 */
@Component
@Slf4j
public class FriendlyLinkDirective extends AbstractDirective {
    @Autowired
    private FriendlyLinkServiceClient friendlyLinkServiceClient;

    /**
     * 站点ID。
     */
    private static final String SITE_ID = "siteId";
    /**
     * 友情链接id集合,可传多个用,分隔。
     */
    public static final String LINKIDS = "linkIds";


    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
        try {
            Long siteId = getLong(SITE_ID, params) == null ? (Long) getCustomAttrbute(env, SITE_ID) : getLong(SITE_ID, params);
            String linkIds = getString(LINKIDS, params);
            FriendlyLink friendlyLink = new FriendlyLink();
            friendlyLink.setSiteId(siteId);
            friendlyLink.setLinkIds(linkIds);
            String note = super.getNote(env);
            List<FriendlyLink> friendlyLinkList;

            friendlyLinkList = friendlyLinkServiceClient.getFriendlyLinkListNoPage(friendlyLink);

            env.setVariable("friendlyLinkList", DefaultObjectWrapperBuilderFactory.getDefaultObjectWrapper().wrap(friendlyLinkList));
            String userToken = super.getUserToken(env);
            if (body != null) {
                if (StringUtils.isEmpty(note)) {
                    body.render(env.getOut());
                } else {
                    Map<String, String> maps = new LinkedHashMap<>();

                    maps.put(CMS_FRIENDLYLINK, "");
                    maps.put(SITE_ID, String.valueOf(super.getLong(SITE_ID, params)));
                    maps.put(LINKIDS, getString(LINKIDS, params));
                    try {
                        super.print(body, maps, env, userToken, params);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else {
                log.debug("友情链接列表所在模板至少要加一个空格");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
